package www.dianbaozu.com.ui

import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.orhanobut.logger.Logger
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentSplashBinding
import www.dianbaozu.com.extension.isLogged
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.extension.countDownCoroutines
import www.wen.com.common.lib.extension.getColorAgency
import www.wen.com.common.lib.extension.glide.setImageUrl
import www.wen.com.common.lib.extension.imgUrl
import www.wen.com.common.lib.extension.resetStartDestination
import www.wen.com.common.lib.util.SpUtil

/**
 * @author WEN
 * @Description:启动页面
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class SplashFragment : BaseLoadingFragment<FragmentSplashBinding>(), View.OnClickListener {

    private var mLoginState: LoginState = LoginState.LOGINING

    private lateinit var mJob: Job

    private val mBaseApiViewModel: SplashViewModel by viewModels()

    override val viewModel: BaseViewModel
        get() = mBaseApiViewModel

    override fun getLayoutId(): Int = R.layout.fragment_splash

    override fun lazyInitView() {
        dataBinding.ivLogo.setColorFilter(getColorAgency(R.color.colorFFFFFF))
        dataBinding.slJump.isVisible = false
        downLoadStartPage()
        logining()
        mJob = countDownCoroutines(
                total = 5,
                onTick = {
                    if (it == 4) {
                        dataBinding.slJump.isVisible = true
                    }
                    if(!dataBinding.btnCountdown.isEnabled && it !=0){
                        jumpNextScreen(false)
                    }

                    "跳过$it".also { count -> dataBinding.btnCountdown.text = count }
                },
                onFinish = {
                    jumpNextScreen(true)
                },
                scope = lifecycleScope
        )
    }


    /**
     * 加载启动页
     */
    private fun downLoadStartPage() {
        mBaseApiViewModel.requestStartPage {
            if (it.content[0].enableStatus && activity!=null) {
                requireActivity().runOnUiThread {
                    Logger.i("图片 = ${it.content[0].imageUrl.imgUrl()}")
                    setImageUrl(
                        view = dataBinding.ivSplash,
                        source = it.content[0].imageUrl.imgUrl(),
                        placeholder = -1,
                    )
                }
            }
        }
    }

    override fun onClick(v: View) {
        dataBinding.btnCountdown.isEnabled = false
        jumpNextScreen(false)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (this::mJob.isInitialized) {
            mJob.cancel()
        }
    }

    private fun jumpNextScreen(nextNow:Boolean) {
        when  {
            mLoginState == LoginState.LOGINED-> {
                requireActivity().resetStartDestination(R.navigation.navigation, R.id.mainFragment)
                return
            }
            (mLoginState == LoginState.LOGINED_OUT)
            -> {
                SpUtil.clearAll()
                requireActivity().resetStartDestination(R.navigation.navigation, R.id.loginFragment)
                return
            }
        }
        //如果是最后一秒时再检查一次是否已经请求到所需要的信息跳转到不同的页面
        if(nextNow){
            when  {
                mLoginState == LoginState.LOGINED-> {
                    requireActivity().resetStartDestination(R.navigation.navigation, R.id.mainFragment)
                }
                (mLoginState == LoginState.LOGINED_OUT)
                -> {
                    SpUtil.clearAll()
                    requireActivity().resetStartDestination(R.navigation.navigation, R.id.loginFragment)
                }
                else->{
                    SpUtil.clearAll()
                    requireActivity().resetStartDestination(R.navigation.navigation, R.id.loginFragment)
                }
            }
        }
    }


    private fun logining() {
        try {
            isLogged(
                    lifecycleScope,
                    logging = {
                        mLoginState = LoginState.LOGINING
                    },
                    logged = {
                        mLoginState = LoginState.LOGINED
                    },
                    logout = {
                        mLoginState = LoginState.LOGINED_OUT
                    })
        } catch (e: Exception) {
            mLoginState = LoginState.LOGINED_OUT
        }
    }

    //云信登录状态
    enum class LoginState {
        LOGINING, LOGINED, LOGINED_OUT
    }

    //本地服务器登录状态
    enum class UserState {
        REQUESTING, BAN, NORMAL,UNKNOWN
    }


}



